package cn.hy.preparelesson.module.pub;

import cn.hy.pms.thrift.utils.ThriftUtils;
import cn.hy.preparelesson.common.constant.ProjectConstant;
import cn.hy.preparelesson.common.entity.*;
import cn.hy.preparelesson.common.enums.FileUploadType;
import cn.hy.preparelesson.common.utils.ClassUtils;
import cn.hy.preparelesson.common.utils.DateUtils;
import cn.hy.preparelesson.common.utils.IdUtils;
import cn.hy.preparelesson.common.vo.ClassVo;
import cn.hy.preparelesson.common.vo.Result;
import cn.hy.preparelesson.common.vo.StafffVo;

import org.apache.commons.io.FileUtils;
import org.apache.thrift.TException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 调用一些公共信息
 */
@RestController
@RequestMapping("/pub")
public class PubController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 根据schoolId获取年级信息
     * @param schoolId
     * @return
     * @throws TException
     */
    @RequestMapping("/gradeList")
    public Result findNormalGradeBySchoolId(@RequestParam("schoolToken") String schoolId) throws TException {
        List<BusiGradeOption> gradeList = ThriftUtils.findNormalBusiGradeOptionBySchoolId(schoolId);
        return Result.success(gradeList);
    }

    /**
     * 根据schoolId获取科目信息
     * @param schoolId
     * @return
     * @throws TException
     */
    @RequestMapping("/subjectList")
    public Result findSubjectBySchoolId(@RequestParam("schoolToken") String schoolId) throws TException {
        List<BusiSubject> subjectList = ThriftUtils.findSubjectBySchoolId(schoolId);
        return Result.success(subjectList);
    }

    /**
     * 根据schoolId,年级获取班级信息
     * @param schoolId
     * @param grade
     * @return
     * @throws TException
     */
    @RequestMapping("/classList")
    public Result findClassBySchoolIdAndGrade(@RequestParam("schoolToken")String schoolId, @RequestParam String grade, @RequestParam String  distanceYear) throws TException {
       int schoolGrade =  ClassUtils.getGradeByDistanceYear(Integer.valueOf(distanceYear), new Date());
        List<BusiClass> officeList = ThriftUtils.findSchoolClassByGradeAndSchoolId(schoolId, String.valueOf(schoolGrade), distanceYear);
        return Result.success(  buildClassVo(officeList));
    }

    /**
     * 根据schoolId获取学年学期信息
     * @param schoolId
     * @return
     */
    @RequestMapping("/semesterList")
    public Result findSemesterBySchoolId(@RequestParam("schoolToken")String schoolId) throws TException {
        List<BusiSchoolSemester> semesterList = ThriftUtils.findSemesterBySchoolId(schoolId);
        return Result.success(semesterList);
    }

    /**
     * 构建ClassVo
     * @param busiClassList
     * @return
     */
    private List<ClassVo> buildClassVo(List<BusiClass> busiClassList) {
        if (CollectionUtils.isEmpty(busiClassList)) {
            return new ArrayList<>();
        }
        List<ClassVo> classList = new ArrayList<>();
        Date now = new Date();
        busiClassList.forEach(item -> classList.add(new ClassVo(item.getOfficeId(),BigDecimal.valueOf( ClassUtils.getDistanceYear(item.getGrade(), now)), item.getGradeName(), item.getClassName(), item.getClassCode())));
//        busiClassList.forEach(item -> classList.add(new ClassVo(item.getId(), BigDecimal.valueOf( ClassUtils.getDistanceYear(item.getGrade(), now)), item.getGradeName(), item.getClassName(), item.getClassCode())));
        return classList;
    }



    /**
     * 统一上传图片 通过code区分文件上传路径
     * @param file
     */
    @RequestMapping("/upload/img")
    public Result uploadAppImg(@RequestParam("file") MultipartFile file, @RequestParam byte code) {
        FileUploadType imgUploadType = FileUploadType.getByCode(code);
        if (imgUploadType == null) {
            return Result.error("上传参数异常！", "");
        }

        if (file != null) {
            try (InputStream inputStream = file.getInputStream()) {
                String originFileName = file.getOriginalFilename();
                //存到服务器的绝对路径
                //扩展名
                String fileExt = originFileName.substring(originFileName.lastIndexOf("."));
                //新文件名
                String newFileName = IdUtils.newId() + fileExt;
                //最终存储路径
                String newFilePath = ProjectConstant.fileUploadLocation + imgUploadType.getTypePath() + DateUtils.getDateDirPath() + "/" + newFileName;
                logger.debug("源文件名为：{}，文件存储路径为：{}", originFileName, newFilePath);

                File toFile = new File(newFilePath);
                FileUtils.copyToFile(inputStream, toFile);
                return Result.success(String.valueOf(code), ProjectConstant.hostName + newFilePath.replace(ProjectConstant.fileUploadLocation, ProjectConstant.fileVisitPrefix));
            } catch (Exception e) {
                logger.error("上传文件失败：", e);
                return Result.error("文件上传失败！", null);
            }
        }
        return Result.error("上传文件不能为空！", null);
    }

    /**
     * 获取教职工信息
     * @param schoolId
     * @return
     * @throws TException
     */
    @RequestMapping("/staffList")
    public Result findStaffListBySchoolId(@RequestParam("schoolToken")String schoolId) throws TException {
        List<StafffVo> staffVoList = ThriftUtils.findStaffListBySchoolId(schoolId);
        return Result.success(staffVoList);
    }

}
